package org.libermundi.theorcs.chronicles.dao.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.libermundi.theorcs.chronicles.dao.SavedInformationsDao;
import org.libermundi.theorcs.chronicles.model.SavedInformations;
import org.libermundi.theorcs.core.dao.exception.OrcsDataAccessException;
import org.libermundi.theorcs.core.dao.hibernate.HibernateGenericDao;
import org.libermundi.theorcs.security.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

@Repository
public final class SavedInformationsDaoImpl extends HibernateGenericDao<SavedInformations, Long> implements SavedInformationsDao {
	private static final Logger logger = LoggerFactory.getLogger(SavedInformationsDaoImpl.class);
	
	public SavedInformationsDaoImpl(){
		super();
		_mappedClazz = SavedInformations.class;
	}

	@Override
	public SavedInformations getByUser(User user) {
		SavedInformations result;
		try{
			result = (SavedInformations) createSimpleCriteria()
						.add(Restrictions.eq(SavedInformations.PROP_USER, user))
						.uniqueResult();
		} catch (HibernateException e) {
			logger.error("Exception in getByUser(" + user +")", e);
			throw new OrcsDataAccessException("Exception in getByUser : " + user, e);
		}
		return result;
	}

	@Override
	public void clear(User user) {
		String hqlQuery = "delete from SavedInformations where user = :user";
		Query q = createQuery(hqlQuery);
		q.setParameter("user", user);
		q.executeUpdate();
	}

	
}
